/**
 * keyFormatter
 * formats id (ex: 00001)
 * 
 * */
function keyFormatter(val)
{	
	return $.strLPad(val, 5);
}

/**
 * getTotal
 * computes total amount of a particular column in a grid
 * 
 * */
function getTotal(col, grid)
{
	var rowIds = grid.getDataIDs();
	
	var total = 0.00;
	for (var i = 0; i < rowIds.length; i++)
	{
		var val = $.formatCurrency(grid.getCell(rowIds[i], col));
		total = total + parseFloat(val);
	}
	
	return total;
}

/**
 * clearGrid
 * clears grid data and removes the elements associated to it
 * 
 * */
function clearGrid(grid, form)
{
	form = form || '';
	
	if(form != '') $('div[id^="' + form + '"]').remove();
	$('#' + grid).clearGridData();
}

/**
 * addGridTrigger
 * 
 * Add marker that grid has changes in pagination or sorting
 */
function addGridTrigger(myGrid)
{
	$('#' + myGrid).setGridParam({
		postData: {
			page_sort_t: 'Y'
		}
	});
}

/**
 * getItemColors
 * gets colors of the item id passed and populates a select html element
 * 
 * */
function getItemColors(itemSizeId, transItemId, transInputId, display)
{
	itemSizeId = itemSizeId || $('#item_sizes_id').val();
	transItemId = transItemId || 0;
	transInputId = transInputId || 'color_id_';
	
	//for clearing dropdown if item is null or blank
	if($('#item').val() == '') itemId = 0;
	
	$('#color_id').children('option').remove();
	
	$.ajax({
		url: siteUrl + 'transaction/get_color_choices',
		type: 'POST',
		data: 'item_sizes_id=' + itemSizeId,
		dataType: 'json',
		success: function(response) {
			var count = response.length;
			
			if (count < 1) 
			{
				$('#dcolor').addClass('hidden');
				if (display != '') $('#dcolor').removeAttr("style");
				return true;
			}
			
			$('#dcolor').removeClass('hidden');
			
			if (display != '')
			{
				$('#dcolor').css({'display' : display});
			}
			
			var code = '<option value="">- Select one -</option>';
			for (var i = 0; i < count; i++)
			{
				code += '<option value="' + response[i].color_id + '">' + response[i].color + '</option>';
			}
			
			$('#color_id').append(code);
		},
		complete: function(request, status) {
			if (transItemId > 0)
			{
				$('#color_id').children('option[value="' + $('#'+ transInputId + transItemId).val() + '"]').attr('selected', true);
			}
		}
	});
}

/**
 * getItemSizes
 * gets sizes of the item id passed and populates a select html element
 *
 * */
function getItemSizes(itemId, transItemId, transInputId, display)
{
	itemId = itemId || $('#item_id').val();
	transItemId = transItemId || 0;
	transInputId = transInputId || 'item_sizes_id_';

	//for clearing dropdown if item is null or blank
	if($('#item').val() == '') itemId = 0;

	$('#item_sizes_id').children('option').remove();

	$.ajax({
		url: siteUrl + 'transaction/get_sizes_choices',
		type: 'POST',
		data: 'item_id=' + itemId,
		dataType: 'json',
		success: function(response) {
			var count = response.length;

			if (count < 1)
			{
				$('#dsizes').addClass('hidden');
				if (display != '') $('#dsizes').removeAttr("style");
				return true;
			}

			$('#dsizes').removeClass('hidden');

			if (display != '')
			{
				$('#dsizes').css({'display' : display});
			}

			var code = '<option value="">- Select one -</option>';
			for (var i = 0; i < count; i++)
			{
				code += '<option value="' + response[i].item_sizes_id + '">' + response[i].description + '</option>';
			}

			$('#item_sizes_id').append(code);
		},
		complete: function(request, status) {
			if (transItemId > 0)
			{
				$('#item_sizes_id').children('option[value="' + $('#'+ transInputId + transItemId).val() + '"]').attr('selected', true);
			}
		}
	});
}

/**
 * getProductSubCat
 * gets sub-category of the category id passed and populates a select html element
 *
 * */
function getProductSubCat(productId, transItemId, transInputId, display)
{
	productId = productId || $('#product_category_id').val();
	transItemId = transItemId || 0;
	transInputId = transInputId || 'product_subcategory_id_';
	
	//for clearing dropdown if item is null or blank
	if($('#product_category_id').val() == '') productId = 0;

	$('#product_subcategory_id').children('option').remove();

	$.ajax({
		url: siteUrl + 'products/get_subcategories',
		type: 'POST',
		data: 'product_category_id=' + productId,
		dataType: 'json',
		success: function(response) {
			var count = response.length;

			if (count < 1)
			{
				$('#product_subcategory_id').val(0);
				return true;
			}

			var code = '<option value="">- Select one -</option>';
                        //var code;
			for (var i = 0; i < count; i++)
			{
				code += '<option value="' + response[i].product_subcategory_id + '">' + response[i].name + '</option>';
			}

			$('#product_subcategory_id').append(code);
		},
		complete: function(request, status) {
			if (transItemId >= 0)
			{
				$('#product_subcategory_id').children('option[value="' + $('#'+ transInputId + transItemId).val() + '"]').attr('selected', true);
			}
		}
	});
}

function genericAutoComplete(element, url, data_string, merged_arr, map_row, minlength) {

    minlength = minlength || 2;
    $('#'+element).autocomplete({

        source: function(request, response) {
            $.ajax({
                url: url,
                type: 'POST',
                data: data_string + request.term,
                dataType: 'json',
                success: function(data) {

                    if (data.length < 1)
                    {
                       for (var i = 0;i < merged_arr[0].length; i++)
                        {
                            eval(merged_arr[0][i]);
                        }
                    }



                    response($.map(data, function(row) {
                        return eval("(" + map_row +")");
                    }));
                }
            });
        },
        minLength: minlength,
        select: function(event, ui) {

            for (var i = 0;i < merged_arr[1].length; i++)
            {
                eval(merged_arr[1][i]);
            }

        },
        change: function(event, ui) {
            if (ui.item == null)
            {
                for (var i = 0;i < merged_arr[0].length; i++)
                {
                    eval(merged_arr[0][i]);
                }
            }
        }
    });
}

$.extend({
	strLPad: function(i, l, s) {
		var o = i.toString();
		
		if ( ! s) s = '0'; 
		while (o.length < l) o = s + o;
		return o;
	},
	
	addZero: function(i) {
		var firstchar = $(i).val().charAt(0);
		return (firstchar == '.') ? $(i).val('0' + $(i).val())  : true;
	},
	
	commaFormattedCurrency: function(amount) {
		var delimiter = ","; 
		
		amount = String(amount);
		if (amount.indexOf(delimiter) != -1) amount = $.formatCurrency(amount);
		if (amount.indexOf('.') == -1) amount += '.00';
		
		var a = amount.split('.', 2);
		var d = a[1];
		var i = parseInt(a[0]);
		
		if (isNaN(i)) return '';
		
		var minus = '';
		if (i < 0) minus = '-';
		
		i = Math.abs(i);
		var n = new String(i);
		var a = [];
		
		while(n.length > 3)
		{
			var nn = n.substr(n.length-3);
			a.unshift(nn);
			n = n.substr(0,n.length-3);
		}
		
		if (n.length > 0) a.unshift(n);
		n = a.join(delimiter);
		
		if (d.length < 1) amount = n;
		else amount = n + '.' + d;
		
		amount = minus + amount;
		
		return amount;
	},
	
	formatCurrency: function(num) {
		num = num.toString().replace(/\$|\,/g,'');
		if (isNaN(num)) num = "0";
		sign = (num == (num = Math.abs(num)));
		num = Math.floor(num*100+0.50000000001);
		cents = num%100;
		num = Math.floor(num/100).toString();
		if (cents < 10) cents = "0" + cents;
		
		for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
			num = num.substring(0,num.length-(4*i+3)) + num.substring(num.length-(4*i+3));
		
		return (((sign)?'':'-') + num + '.' + cents);
	},
	
	URLEncode: function(c) {
		var o = ''; 
		var x = 0;
		c = c.toString();
		var r = /(^[a-zA-Z0-9_.]*)/;
		
		while (x < c.length) 
		{ 
			var m = r.exec(c.substr(x));
			if (m != null && m.length > 1 && m[1] != '') 
			{
				o += m[1];
				x += m[1].length;
			}
			else 
			{
				if (c[x] == ' ') o += '+';
				else
				{
					var d = c.charCodeAt(x);
					var h = d.toString(16);
					o += '%' + (h.length < 2 ? '0' : '') + h.toUpperCase();
				}
				x++;
			}
		}
		
		return o;
	},
				
	URLDecode: function(s) {
		var o = s;
		var binVal, t;
		var r = /(%[^%]{2})/;
				
		while ((m = r.exec(o)) != null && m.length > 1 && m[1] !='')
		{
			b = parseInt(m[1].substr(1),16);
			t = String.fromCharCode(b);
			o = o.replace(m[1],t);
		}
		
		return o;
	},
	
	blockNonNumbers: function (obj, e, allowDecimal, allowNegative)
	{
		var key;
		var isCtrl = false;
		var keychar;
		var reg;
			
		if(window.event)
		{
			key = e.keyCode;
			isCtrl = window.event.ctrlKey
		}
		else if(e.which) 
		{
			key = e.which;
			isCtrl = e.ctrlKey;
		}
		
		if (isNaN(key)) return true;
		
		keychar = String.fromCharCode(key);
		
		// check for backspace or delete, or if Ctrl was pressed
		if (key == 8 || isCtrl)
		{
			return true;
		}

		reg = /\d/;
		var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
		var isFirstD = allowDecimal ? keychar == '.' && obj.value.indexOf('.') == -1 : false;
		
		return isFirstN || isFirstD || reg.test(keychar);
	},
	
	extractNumber: function (obj, decimalPlaces, allowNegative)
	{
		var temp = obj.value;
		
		// avoid changing things if already formatted correctly
		var reg0Str = '[0-9]*';
		if (decimalPlaces > 0)
		{
			reg0Str += '\\.?[0-9]{0,' + decimalPlaces + '}';
		}
		else if (decimalPlaces < 0)
		{
			reg0Str += '\\.?[0-9]*';
		}
		
		reg0Str = allowNegative ? '^-?' + reg0Str : '^' + reg0Str;
		reg0Str = reg0Str + '$';
		
		var reg0 = new RegExp(reg0Str);
		if (reg0.test(temp)) return true;

		// first replace all non numbers
		var reg1Str = '[^0-9' + (decimalPlaces != 0 ? '.' : '') + (allowNegative ? '-' : '') + ']';
		var reg1 = new RegExp(reg1Str, 'g');
		temp = temp.replace(reg1, '');

		if (allowNegative)
		{
			// replace extra negative
			var hasNegative = temp.length > 0 && temp.charAt(0) == '-';
			var reg2 = /-/g;
			temp = temp.replace(reg2, '');
			if (hasNegative) temp = '-' + temp;
		}
		
		if (decimalPlaces != 0) 
		{
			var reg3 = /\./g;
			var reg3Array = reg3.exec(temp);
			if (reg3Array != null) 
			{
				// keep only first occurrence of .
				//  and the number of places specified by decimalPlaces or the entire string if decimalPlaces < 0
				var reg3Right = temp.substring(reg3Array.index + reg3Array[0].length);
				reg3Right = reg3Right.replace(reg3, '');
				reg3Right = decimalPlaces > 0 ? reg3Right.substring(0, decimalPlaces) : reg3Right;
				temp = temp.substring(0,reg3Array.index) + '.' + reg3Right;
			}
		}
		
		obj.value = temp;
	},
	
	trim: function (str)
	{
		return $.lTrim($.rTrim(str));
	},
	
	lTrim: function (str)
	{
		if(str==null) return null;
		for(var i=0;str.charAt(i)==" ";i++);
			return str.substring(i,str.length);
	},
	
	rTrim: function (str)
	{
		if(str==null) return null;
		for(var i=str.length-1;str.charAt(i)==" ";i--);
			return str.substring(0,i+1);
	}
});


function printerFriendly(func, view, objData)
{
	$.ajax({
		url: siteUrl + '/' + func + '/' + view,
		type: 'POST',
		data: objData,
		dataType: 'html',
		success: function(response) {
                        if (navigator.userAgent.indexOf("Firefox")!=-1) {
                            var win = window.open('', '_blank');
                        }
                        else {
                            var win = window.open('', '_blank',width=screen.width, height=screen.height);
                        }

			rep = $('#print_friendly').clone();
			win.document.open();
			win.document.write(response + rep.html());
                        
			win.document.close();


		}
	});
}